# day4线性回归模型 
import numpy as np
from sklearn.linear_model import LinearRegression           # 线性回归模型
from sklearn.model_selection import train_test_split        # 训练集和测试集的划分
from sklearn.metrics import r2_score, mean_squared_error    # 模型性能评估
import matplotlib.pyplot as plt


def linear_regression_demo():
    # 构造简单线性数据
    X = np.array([[1], [2], [3], [4], [5]])
    y = np.array([2, 4, 6, 8, 10])
    
    # 划分训练集和测试集
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, random_state=42)
    
    # 创建线性回归模型
    model = LinearRegression()
    model.fit(X_train, y_train)
    
    # 输出模型参数
    print("Coefficient (斜率):", model.coef_)
    print("Intercept (截距):", model.intercept_)
    
    # 预测测试集
    y_pred = model.predict(X_test)
    print("Test set predictions:", y_pred)
    print("Test set true values:", y_test)
    
    # 模型性能指标
    print("R2 score:", r2_score(y_test, y_pred))
    print("Mean Squared Error:", mean_squared_error(y_test, y_pred))
    
    # 可视化
    plt.scatter(X, y, color='blue', label='True Data')
    plt.plot(X, model.predict(X), color='red', label='Fitted Line')
    plt.xlabel('X')
    plt.ylabel('y')
    plt.title('Linear Regression')
    plt.legend()
    plt.grid(True)
    plt.show()


# 主流程入口
if __name__ == "__main__":
    linear_regression_demo() 


 